package com.hulk.rpc.loadbalance.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.hulk.rpc.loadbalance.LoadBalance;
import com.hulk.rpc.loadbalance.Weightable;
import io.netty.util.internal.ThreadLocalRandom;

import java.util.List;

/**
 * 基于权重的随机负载均衡算法
 *
 * @author xuxukang
 * @date 2019-03-27 22:18
 */
public class WeightRandomLoadBalance<T extends Weightable> extends LoadBalance<T> {

  private List<T> weightableResources = Lists.newArrayList();

  @Override
  public T select() {
    if (CollUtil.isEmpty(weightableResources)) {
      copyWeightableResources();
    }
    int randomIndex = ThreadLocalRandom.current().nextInt(weightableResources.size());

    return weightableResources.get(randomIndex);
  }

  @Override
  public void clean() {
    weightableResources.clear();
    copyWeightableResources();
  }

  private void copyWeightableResources() {
    resources.parallelStream().forEach(resource -> {
      for (int i = 0; i < resource.weight(); i++) {
        weightableResources.add(resource);
      }
    });
  }
}
